<template>
    <view class="idle-confirm-order">
        <!-- 顶部切换：上门配送/线下自提 -->
        <view class="tabs">
            <view :class="['tab', deliverType === 'door' ? 'active' : '']" @click="deliverType = 'door'">上门配送</view>
            <view :class="['tab', deliverType === 'self' ? 'active' : '']" @click="deliverType = 'self'">线下自提</view>
        </view>

        <view class="container">
            <!-- 地址（仅上门配送显示） -->
            <address-comp v-show="deliverType === 'door'" :blackUrl="backUrl" />

            <!-- 联系人（仅线下自提显示） -->
            <view class="address-box" v-show="deliverType === 'self'">
                <view class="cell">
                    <text class="label">联系人</text>
                    <input class="input" v-model="contactName" placeholder="请输入联系人姓名" />
                </view>
                <view class="cell">
                    <text class="label">联系电话</text>
                    <input class="input" v-model="contactPhone" placeholder="请输入联系电话" />
                </view>
            </view>

            <view class="goods-box">
                <!-- 商品卡片 -->
                <view class="card goods">
                    <u-image :src="goods.cover" width="140rpx" height="140rpx" mode="aspectFill" radius="12rpx"></u-image>
                    <view class="goods-info">
                        <view class="title">{{ goods.title }}</view>
                        <view class="price">¥{{ goods.price }}</view>
                    </view>
                </view>

                <!-- 优惠券、虚拟资产 -->
                <view class="card cell between" @click="openCoupon">
                    <view class="label">优惠券</view>
                    <view class="value">
                        <text class="discount">{{ selectedCoupon ? `${selectedCoupon.type}-${selectedCoupon.amount}.00` :
                            '请选择' }}</text>
                        <u-icon name="arrow-right" size="14" color="#999" />
                    </view>
                </view>

                <view class="card cell between" v-if="!nowSelectedAsset" @click="openAssets">
                    <view class="label">虚拟资产</view>
                    <view class="value">
                        <text class="virtual-asset">{{ virtualAssetText }}</text>
                        <u-icon name="arrow-right" size="14" color="#999" />
                    </view>
                </view>
                <!-- 选择后显示对应抵扣开关行 -->
                <view class="card cell between" v-if="nowSelectedAsset === 'points'">
                    <view class="dk-con" @click="openAssets">
                        <view class="label">积分抵扣</view>
                        <view class="price-label-txt">共有{{ pointsValue }}积分，可打0折</view>
                    </view>
                    <view class="value">
                        <text class="virtual-asset">-{{ usePoints ? pointsDiscountAmount : 0 }}</text>
                        <u-switch v-model="usePoints" size="15"></u-switch>
                    </view>
                </view>
                <view class="card cell between" v-if="nowSelectedAsset === 'warmCore'">
                    <view class="dk-con" @click="openAssets">
                        <view class="label">暖芯值抵扣</view>
                        <view class="price-label-txt">共有{{ warmCoreValue }}暖芯值，可抵扣¥{{ warmCoreDiscount }}</view>
                    </view>
                    <view class="value">
                        <text class="virtual-asset">-{{ useWarmCore ? warmCoreDiscount : 0 }}</text>
                        <u-switch v-model="useWarmCore" size="15"></u-switch>
                    </view>
                </view>

                <!-- 配送费（上门配送显示） -->
                <view class="card cell between" v-if="deliverType === 'door'">
                    <view class="label flex">配送费<text class="tips">?</text></view>
                    <view class="value">{{ deliveryFee }}</view>
                </view>
            </view>

            <!-- 备注 -->
            <view class="card note">
                <view class="label">备注</view>
                <textarea v-model="remark" placeholder="请输入~" maxlength="100" />
                <view class="count">{{ remark.length }}/100</view>
            </view>
        </view>

        <!-- 底部购买按钮 -->
        <fixed-footer>
            <view class="footer">
                <u-button type="primary" shape="circle" :custom-style="buttonStyle" @click="showPay = true">
                    立即购买 {{ totalAmount.toFixed(2) }}
                </u-button>
            </view>
        </fixed-footer>

        <!-- 优惠券弹层（与家政下单一致） -->
        <u-popup :show="couponVisible" mode="bottom" round="16" :closeable="true" :safeAreaInsetBottom="true"
            @close="couponVisible = false">
            <view class="coupon-popup">
                <view class="coupon-list-container">
                    <coupon-list ref="couponListRef" :couponList="couponList" :type="['usable', 'available', 'canceluse']"
                        @claimCoupon="handleClaimCoupon" @useCoupon="handleUseCoupon"
                        @cancelUseCoupon="handleCancelUseCoupon" />
                </view>
            </view>
        </u-popup>

        <!-- 虚拟资产弹层 -->
        <virtual-asset-popup
            :show.sync="showVirtualAssetPopup"
            :assets="virtualAssets"
            :defaultSelected="selectedAsset || ''"
            @assetsReady="onAssetsReady"
            @confirm="onAssetConfirmed"
        />

        <!-- 支付弹层 -->
        <order-pay-popup :show.sync="showPay" :amount="totalAmount" @confirm="onPayConfirm" />
    </view>
</template>
<script>
import AddressComp from '@/components/address/index.vue'
import CouponList from '@/components/coupon/index.vue'
import FixedFooter from '@/components/fixed-footer/index.vue'
import OrderPayPopup from '@/components/order/pay.vue'
import VirtualAssetPopup from '@/components/virtual-asset-popup/index.vue'
import { postIdleOrderConfirm, getIdleOrderTransportfee } from '@/api/index.js'
export default {
    name: 'IdleConfirmOrder',
    components: { AddressComp, CouponList, FixedFooter, OrderPayPopup, VirtualAssetPopup },
    data() {
        return {
            deliverType: 'door',
            contactName: '',
            contactPhone: '',
            backUrl: '/views/order/idle-confirm-order',
            goods: { title: '婴儿车旧物低价处理，95新整体质量高', price: 69.99, cover: '/static/community/icon2.png' },
            // 优惠券
            couponVisible: false,
            couponList: [
                { id: 1, amount: 20, condition: 100, type: '满减券', restriction: '限闲置订单使用', status: 'usable', validUntil: '2025-12-31' },
                { id: 2, amount: 10, condition: 50, type: '满减券', restriction: '限闲置订单使用', status: 'available', validUntil: '2025-12-31' }
            ],
            selectedCoupon: null,
            // 虚拟资产
            showVirtualAssetPopup: false,
            virtualAssets: { points: 0, warm_core: 0 },
            pointsValue: 0,
            warmCoreValue: 0,
            warmCoreDiscount: 0,
            selectedAsset: null,
            nowSelectedAsset: null,
            usePoints: true,
            useWarmCore: true,
            // 费用
            deliveryFee: 0,
            remark: '',
            showPay: false,
            shopId: null
        }
    },
    computed: {
        virtualAssetText() { return '请选择' },
        pointsDiscountAmount() { return 0 },
        displayCoupon() { return Number(this.selectedCoupon ? this.selectedCoupon.amount : 0).toFixed(2) },
        totalAmount() {
            const base = Number(this.goods.price || 0)
            const coupon = Number(this.selectedCoupon ? this.selectedCoupon.amount : 0)
            const fee = this.deliverType === 'door' ? Number(this.deliveryFee || 0) : 0
            const pointsMinus = this.nowSelectedAsset === 'points' && this.usePoints ? Number(this.pointsDiscountAmount) : 0
            const warmMinus = this.nowSelectedAsset === 'warmCore' && this.useWarmCore ? Number(this.warmCoreDiscount) : 0
            return Math.max(0, base - coupon + fee - pointsMinus - warmMinus)
        },
        buttonStyle() {
            return { background: 'linear-gradient(90deg, #0785CF 0%, #25A4EF 100%)', fontSize: '30rpx', height: '88rpx' }
        }
    },
    onLoad(options) {
        this.shopId = options.id
        this.getIdleOrderTransportfeeEvent()
    },
    mounted() {
        // 初始化虚拟资产（可接入接口）
        this.virtualAssets = { points: 0, warm_core: 0 }
        this.pointsValue = this.virtualAssets.points
        this.warmCoreValue = this.virtualAssets.warm_core
        this.warmCoreDiscount = this.virtualAssets.warm_core

        // 从store读取闲置商品信息
        const item = this.$store && this.$store.state && this.$store.state.idleOrderItem
        if (item) {
            this.goods = {
                id: item.id,
                title: item.title || item.name || '',
                price: Number(item.price || 0),
                cover: (item.images && item.images[0]) || item.cover || '/static/community/icon2.png'
            }
        }
    },
    methods: {
        async getIdleOrderTransportfeeEvent() {
            const res = await getIdleOrderTransportfee({
                item_id:this.shopId
            })
            this.deliveryFee = res.data
        },
        openCoupon() { this.couponVisible = true },
        handleClaimCoupon(coupon) {
            this.couponList = this.couponList.map(c => c.id === coupon.id ? { ...c, status: 'usable' } : c)
            uni.showToast({ title: `已领取优惠券: ${coupon.type}`, icon: 'none' })
        },
        handleUseCoupon(coupon) {
            if (this.selectedCoupon && this.selectedCoupon.id !== coupon.id) {
                this.couponList = this.couponList.map(c => c.id === this.selectedCoupon.id ? { ...c, status: 'usable' } : c)
            }
            this.selectedCoupon = coupon
            this.couponList = this.couponList.map(c => c.id === coupon.id ? { ...c, status: 'canceluse' } : c)
            this.couponVisible = false
        },
        handleCancelUseCoupon(coupon) {
            if (this.selectedCoupon && this.selectedCoupon.id === coupon.id) this.selectedCoupon = null
            this.couponList = this.couponList.map(c => c.id === coupon.id ? { ...c, status: 'usable' } : c)
        },
        openAssets() { this.showVirtualAssetPopup = true },
        onAssetsReady(assets) {
            this.virtualAssets = assets || { points: 0, warm_core: 0 }
            this.pointsValue = this.virtualAssets.points || 0
            this.warmCoreValue = this.virtualAssets.warm_core || 0
            this.warmCoreDiscount = this.warmCoreValue
        },
        onAssetConfirmed(selected, assets) {
            this.onAssetsReady(assets)
            this.selectedAsset = selected
            this.nowSelectedAsset = selected
            this.usePoints = selected === 'points'
            this.useWarmCore = selected === 'warmCore'
        },
        async onPayConfirm({ method, amount }) {
            try {
                this.showPay = false

                const payMethodMap = {
                    wechat: 1,
                    alipay: 2,
                    balance: 3,
                }
                const deliveryTypeMap = { door: 1, self: 2 }

                const addressId = (this.$store && this.$store.state && this.$store.state.address && this.$store.state.address.id) ? this.$store.state.address.id : 0
                const usePointsAmount = this.nowSelectedAsset === 'points' && this.usePoints ? Number(this.pointsValue || 0) : 0
                const warmCoreUsed = this.nowSelectedAsset === 'warmCore' && this.useWarmCore ? Number(this.warmCoreValue || 0) : 0

                const payload = {
                    item_id: this.goods && this.goods.id ? this.goods.id : (this.itemId || 0),
                    delivery_type: deliveryTypeMap[this.deliverType] || 1,
                    contact_name: this.deliverType === 'self' ? (this.contactName || '') : '',
                    contact_phone: this.deliverType === 'self' ? (this.contactPhone || '') : '',
                    address_id: this.deliverType === 'door' ? addressId : 0,
                    warm_core_used: warmCoreUsed,
                    pay_method: payMethodMap[method] || 1,
                    remark: this.remark || '',
                    use_points: usePointsAmount,
                    coupon_id: this.selectedCoupon ? this.selectedCoupon.id : 0
                }

                const res = await postIdleOrderConfirm(payload)
                if (res && (res.errno === 0 || res.code === 0)) {
                    uni.showToast({ title: '下单成功', icon: 'success' })
                    uni.navigateTo({ url: '/views/order/success' })
                    return
                }
                uni.showToast({ title: (res && (res.msg || res.message)) || '下单失败', icon: 'none' })
            } catch (err) {
                uni.showToast({ title: '下单异常，请重试', icon: 'none' })
                console.error('postIdleOrderConfirm error', err)
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.idle-confirm-order {
    min-height: 100vh;
    background: #f5f5f5;
}

.tabs {
    display: flex;
    justify-content: center;
    gap: 40rpx;
    padding: 24rpx 0 0;

    .tab {
        color: #999;
        font-size: 28rpx;
        padding: 8rpx 12rpx;
    }

    .tab.active {
        color: #333;
        font-weight: 600;
        border-bottom: 6rpx solid #0785CF;
    }
}

.container {
    padding: 20rpx;
}

.address-box {
    border-radius: 20rpx;
    overflow: hidden;
    background: #fff;
    margin-bottom: 20rpx;
    padding:0 28rpx;

    .cell {
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 28rpx;
        color: #333333;
        padding: 28rpx 0;
        border-bottom: 1rpx solid #DDDDDD;

        &:last-child {
            border-bottom: none;
        }
    }

    .input {
        font-size: 28rpx;
        color: #333333;
        text-align: right;
    }
}

.goods-box {
    border-radius: 20rpx;
    overflow: hidden;
    background: #fff;
    padding: 0 28rpx;
    margin-bottom: 20rpx;

    .card {
        border-bottom: 1rpx solid #DDDDDD;

        &:last-child {
            border-bottom: none;
        }
    }
}

.card {
    background: #fff;
    padding: 28rpx 0;
}

.cell {
    display: flex;
    align-items: center;
    gap: 20rpx;
}

.cell.between {
    justify-content: space-between;
}

.label {
    color: #333;
    font-size: 28rpx;
}

.value {
    color: #333;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    gap: 8rpx;
}

.price-label-txt {
    font-size: 24rpx;
    color: #999;
}

.tips {
    border: 1rpx solid #B3B7BD;
    border-radius: 50%;
    width: 24rpx;
    height: 24rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #B3B7BD;
    margin: 5rpx 0 0 10rpx;
    font-size: 24rpx;
}

.goods {
    display: flex;
    gap: 16rpx;
}

.goods-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.title {
    font-size: 28rpx;
    color: #333;
    line-height: 1.4;
}

.price {
    color: #EE241D;
    font-size: 28rpx;
    font-weight: 600;
    margin-top: 10rpx;
}

.discount {
    font-size: 28rpx;
    color: #999;
}

.virtual-asset {
    font-size: 28rpx;
    color: #999;
}

.note {
    position: relative;
    border-radius: 20rpx;
    padding:20rpx;
}

.note textarea {
    width: 100%;
    height: 180rpx;
    background: #f7f8fa;
    border-radius: 16rpx;
    padding: 16rpx;
    font-size: 26rpx;
    color: #333;
    box-sizing: border-box;
    margin-top: 20rpx;
}

.note .count {
    position: absolute;
    right: 28rpx;
    bottom: 26rpx;
    color: #999;
    font-size: 22rpx;
}

.footer {
    padding: 12rpx 0;
}

/* 虚拟资产弹层样式（复用confirm-order风格的精简版） */
.virtual-asset-popup {
    padding: 32rpx;
    display: flex;
    flex-direction: column;
    height: 100%;
}

.popup-header {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 28rpx;
}

.popup-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
}

.asset-options {
    flex: 1;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
}

.asset-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 28rpx 0;
    border-bottom: 1rpx solid #DDDDDD;
}

.asset-option.no-click {
    pointer-events: none;
    opacity: .5;
}

.asset-left {
    display: flex;
    gap: 10rpx;
}

.asset-icon span {
    font-size: 32rpx;
    color: #df9824;
}

.asset-info {
    display: flex;
    flex-direction: column;
}

.asset-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 600;
}

.asset-desc {
    font-size: 24rpx;
    color: #999;
    margin-top: 4rpx;
}

.asset-right {
    display: flex;
    align-items: center;
    gap: 16rpx;
}

.radio-btn {
    width: 24rpx;
    height: 24rpx;
    border-radius: 50%;
    border: 1rpx solid #999;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #fff;
}

.radio-btn.selected {
    border-color: #0785CF;
    background: #0785CF;
}

.popup-footer {
    display: flex;
    justify-content: center;
    padding-top: 28rpx;
}

.confirm-btn {
    width: 100%;
    height: 80rpx;
    background: linear-gradient(90deg, #0785CF 0%, #25A4EF 100%);
    box-shadow: 0 4rpx 20rpx rgba(7, 133, 207, 0.1);
    border-radius: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 32rpx;
    color: #fff;
    font-weight: 600;
}

.coupon-popup {
    padding: 100rpx 0 28rpx;
}
</style>